import React from "react";
import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux/es/hooks/useSelector";
import { InfoO } from "@react-vant/icons";
import { SubmitBar } from "react-vant";
import { useDispatch } from "react-redux/es/hooks/useDispatch";
const Index = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const data = useSelector((state: any) => state.car.data);
  const totalPrice = data.reduce((p: any, n: any) => {
    return n.isChecked ? p + n.price * n.count : p;
  }, 0);
  const submit = () => {
    navigate(`/order?price=${totalPrice}`);
  };
  return (
    <div>
      {data.map((v: any) => {
        return (
          <dl key={v.id} className="list-item">
            <input
              type="checkbox"
              checked={v.isChecked}
              onChange={() =>
                dispatch({
                  type: "checkOne",
                  payload: v,
                })
              }
            />
            <dt>
              <img src={v.url} alt="" />
            </dt>
            <dd>
              <h3>{v.title}</h3>
              <div>{v.price}</div>
              <div>
                <button
                  onClick={() => dispatch({ type: "subCount", payload: v })}
                >
                  -
                </button>
                <span>{v.count}</span>
                <button
                  onClick={() => dispatch({ type: "addCount", payload: v })}
                >
                  +
                </button>
              </div>
            </dd>
          </dl>
        );
      })}
      <SubmitBar
        disabled={totalPrice === 0}
        price={totalPrice * 100}
        tipIcon={<InfoO />}
        buttonText="提交订单"
        onSubmit={() => submit()}
      />
    </div>
  );
};
export default Index;
